package com.xinjie.www.servlet;

import com.xinjie.www.po.Manager;
import com.xinjie.www.po.User;
import com.xinjie.www.service.post.PostServiceImpl;
import com.xinjie.www.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class WriteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        System.out.println(method);
        String title = req.getParameter("title");
        String tieba = req.getParameter("tieba");
        String content = req.getParameter("content");
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String time = simpleDateFormat.format(date);
        PostServiceImpl postService = new PostServiceImpl();
        boolean b = false;
        if ("1".equals(method)) {
            User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
            String writer = user.getUserName();
            try {
                if (!"".equals(title) && !"".equals(tieba) && !"".equals(content) && !"".equals(time)){
                    b = postService.writePost(title, tieba, time, content, writer);
                }
            } catch (SQLException | ClassNotFoundException e) {
                e.printStackTrace();
            }
            if (b) {
                req.getSession().setAttribute("WriteSeccess", "发布成功");
                resp.sendRedirect("/UserPage/UserWritePost.jsp");
            } else {
                req.getSession().setAttribute("WriteLose", "发布失败，请重新发布");
                resp.sendRedirect("/UserPage/UserWritePost.jsp");
            }
        } else {
            Manager manager = (Manager) req.getSession().getAttribute(Constants.MANAGER_SESSION);
            String writer = manager.getName();
            try {
                b = postService.writePost(title, tieba, time, content, writer);
            } catch (SQLException | ClassNotFoundException e) {
                e.printStackTrace();
            }
            if (b) {
                req.getSession().setAttribute("WriteSeccess", "发布成功");
                resp.sendRedirect("/ManagerPage/ManagerWritePost.jsp");
            } else {
                req.getSession().setAttribute("WriteLose", "发布失败，请重新发布");
                resp.sendRedirect("/ManagerPage/ManagerWritePost.jsp");
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
